import os
import tempfile
import uuid
import requests
import logging

from os.path import splitext
from urllib.parse import urlparse

logger = logging.getLogger('VideoHandler')


def download_file(src, suffix):
    local_path = tempfile.gettempdir() + "/" + str(uuid.uuid4()) + suffix
    with requests.get(src, stream=True, timeout=(60, 60)) as res:
        res.raise_for_status()  # 如果请求出错，这里会抛出HTTPError异常
        with open(local_path, 'wb') as f:
            for chunk in res.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_path


def delete_file(file_path):
    if os.path.isfile(file_path):
        os.remove(file_path)
        logger.info(f"文件 {file_path} 已删除。")
    else:
        logger.warning(f"文件 {file_path} 不存在。")


def get_extension(url):
    # 解析URL
    parsed = urlparse(url)
    # 获取路径部分并分割扩展名
    path = parsed.path
    root, ext = splitext(path)
    return ext